// 使用方法：
// 1. 在组件中引入 useAutoScroll 钩子
// 2. 将钩子返回的 ref 传递给需要自动滚动的元素
// 3. 钩子会自动监听元素内容变化，并根据用户滚动行为自动滚动到页面底部

// 1、
// const scrollRef = useAutoScroll({
//     enabled: true,  // 是否启用自动滚动
//     scrollBehavior: 'smooth'  // 滚动行为：'smooth' 或 'auto'
//   });
// 2.
// <div ref={scrollRef} className="overflow-y-auto">
//   {/* 内容 */}
// </div>

import { useEffect, useRef } from 'react';

interface UseAutoScrollProps {
  enabled?: boolean;
  scrollBehavior?: ScrollBehavior;
  getNode?: () => Node | null;
}

export const useAutoScroll = ({ enabled = true, scrollBehavior = 'smooth', getNode }: UseAutoScrollProps = {}) => {
  const containerRef = useRef<HTMLDivElement | null>(null);
  const isUserScrolling = useRef(false);
  let timer: ReturnType<typeof setTimeout> | null = null;

  useEffect(() => {
    const getTargetNode = () => {
      if (typeof getNode === 'function') {
        return getNode();
      }
      return containerRef.current;
    };
    const container = getTargetNode();
    if (!container || !enabled) {
      return;
    }

    const handleWheel = () => {
      isUserScrolling.current = true;
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        isUserScrolling.current = false;
      }, 2000);
    };

    const scrollToBottom = () => {
      if (!isUserScrolling.current && container instanceof HTMLElement) {
        container.scrollTo({
          top: container.scrollHeight,
          behavior: scrollBehavior
        });
      }
    };

    const observer = new MutationObserver(() => {
      scrollToBottom();
    });
    observer.observe(container, {
      childList: true,
      subtree: true,
      characterData: true
    });

    container.addEventListener('wheel', handleWheel);
    scrollToBottom();

    return () => {
      observer.disconnect();
      container.removeEventListener('wheel', handleWheel);
      if (timer) {
        clearTimeout(timer);
      }
    };
  }, [enabled, scrollBehavior, getNode]);

  return containerRef;
}; 